/* Copyright 2009 Requirements Management System 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.model.commons.checker;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author Mario Gaitan
 *
 */
public class SQLScriptReader extends ScriptReader {
	private String script="";
	private int pointer=0;
	private static final String COMMENT = "(?>/\\*(?>[^*]|(?>\\*+[^*/]))*\\*+/)|(?>//.*)";
	public String getScript() {
		return script;
	}
	public int getPointer() {
		return pointer;
	}
	public void reset() {
		pointer = 0;
	}
	private String clearStatement(String statement) {
		String _statement = statement;
		_statement = _statement.replace("\n", " ");
		_statement = _statement.replace("\t", " ");
		_statement = _statement.replace("\b", " ");
		_statement = _statement.replace("\r", " ");
		_statement = _statement.replace("\f", " ");
		return _statement;
	}
	public String getNextStatement() {
		String statement=null;
		int endIndex = script.indexOf(";", pointer);
		if(endIndex>-1) {
			statement = script.substring(pointer, endIndex);
			pointer = endIndex + 1;
		}
		return statement==null?null:statement.trim();
	}
	
	public void loadScript(String resourceName) {
		script = readScript(resourceName);
	    Pattern pattern = Pattern.compile(COMMENT);
	    Matcher matcher = pattern.matcher(script);
		script = matcher.replaceAll(" ");
		script = clearStatement(script);
		reset();
	}
	
}
